import axios from 'axios'


import {loginUrlStore, useTokenStore} from "@/stores";
import {ElMessage} from "element-plus";
import {refreshToken} from "@/api/web/user.js";
import router from "@/router/index.js";


//表单序列化
export const serialize = data => {
    let list = [];
    Object.keys(data).forEach(ele => {
        list.push(`${ele}=${data[ele]}`)
    })
    return list.join('&');
};
const http = axios.create({
    timeout: 10000,
    validateStatus: status => {
        return status >= 200 && status <= 500; // 默认的
    },
    withCredentials: true
})

http.interceptors.request.use((config) => {
    const token = useTokenStore().getToken()
    const meta = (config.meta || {});
    if (token) {
        config.headers['nova-auth'] = 'Bearer ' + token// 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    }
    //headers中配置serialize为true开启序列化
    if (config.method === 'post' && meta.isSerialize === true) {
        config.data = serialize(config.data);
    }
    return config
}, error => {
    return Promise.reject(error)
});
http.interceptors.response.use((res)=>{
    const code = Number(res.status) || 200;
    const loginUrl = '/'+ loginUrlStore().getLoginUrl()
    if (code === 200) {
        if(res.request.responseType==='blob'){
            return res;
        }
        if(res.data.code !== 200) {
            ElMessage.error(res.data.msg)
        }
        return res;
    }else if (code === 403) {
        if(''!==localStorage.getItem('nova-refreshToken')&&null!==localStorage.getItem('nova-refreshToken')&&undefined!==localStorage.getItem('nova-refreshToken')){
            refreshToken({"refreshToken":localStorage.getItem('nova-refreshToken')}).then(r => {
               if(r.data.code === 200){
                   const config = res.config
                   useTokenStore().setToken(r.data.data);
                   config.headers['nova-auth'] = 'Bearer ' + useTokenStore().getToken()
                   return axios(config)
               }else{

                   router.push(loginUrl);
               }
            })
        }else{
            router.push(loginUrl);
            return Promise.reject('请重新登陆')
        }
    }else if (code === 404) {
        setTimeout(() => {
            window.location.href="/404"
        }, 1500)
        return Promise.reject('找不到页面')
    }else if (code === 401) {
        useTokenStore().removeToken()
        setTimeout(() => {
            router.push(loginUrl);
        }, 1500)
        return Promise.reject('请重新登陆')
    }else {

        return Promise.reject(res.data.data.msg)
    }
}, error => {
    return Promise.reject(error)
})
export default http;